import React, { ChangeEvent, FC, useEffect, useState } from 'react'
// 引入路由
import { useNavigate, useLocation, useSearchParams } from 'react-router-dom'
// 引用constant常量
import { LIST_SEARCH_PARAM_KEY } from '../constant/index'
// 引入antd中的组件
import { Input } from 'antd'

const { Search } = Input

const ListSearch: FC = () => {
  // 路由方法
  const nav = useNavigate()
  const { pathname } = useLocation()

  // 表单受控组件
  const [iptVal, setIptVal] = useState('')
  function handleIptChange(e: ChangeEvent<HTMLInputElement>) {
    setIptVal(e.target.value)
  }

  // 获取url参数,并设置到input iptVal
  const [searchParams] = useSearchParams()
  useEffect(() => {
    const curVal = searchParams.get(LIST_SEARCH_PARAM_KEY) || ''
    setIptVal(curVal)
  }, [searchParams])

  // 表单输入框事件
  function handleSearch(value: string) {
    // 跳转页面,增加url参数
    nav({
      pathname,
      search: `${LIST_SEARCH_PARAM_KEY}=${value.replace(/\s+/g, '')}`,
    })
  }
  return (
    <>
      <Search
        size="large"
        placeholder="请输入关键词~"
        allowClear
        onChange={handleIptChange}
        onSearch={handleSearch}
        style={{ width: 300 }}
      />
    </>
  )
}

export default ListSearch
